const API_URL = 'https://oaa00e.top/bjnsWalk/api/statistics/ranking/today';
const WIN_API_URL = 'https://oaa00e.top/bjnsWalk/win/last-week';
const { SelectionType } = require('../../constant/enums');
const RankModel = require('../../model/RankModel');
const WinInfoModel = require('../../model/WinInfoModel');
const { checkLoginAndRedirect, autoLogin, isLoggedIn, setAppResumedFromBackground, setUserOnlineStartTime } = require('../../utils/auth.js');

Page({
  data: {
    mainTabIndex: 1, // 0:团队赛 1:个人赛 2:中奖名单 (默认选中个人赛)
    subTabIndex: 0, // 0:总行榜/日榜 1:支行榜/周榜 2:总榜
    topThree: [], // 前三名数据
    otherRanks: [], // 其他排名数据
    myRank: null, // 我的排名数据
    winList: [], // 中奖名单数据
    selectionType: SelectionType.PERSONAL_TODAY, // 默认个人赛日榜
    // 缓存数据
    cacheData: {},
    // 中奖名单缓存
    winListCache: null
  },

  onLoad() {
    // 检查登录状态
    if (!checkLoginAndRedirect('排行榜')) {
      return;
    }
    this.initData();
  },

  onShow() {
    console.log('排行榜页面显示 - 小程序重新进入前台');
    
    // 检查登录状态，如果已登录则尝试自动登录
    if (isLoggedIn()) {
      console.log('检测到用户已登录，尝试自动登录验证');
      this.performAutoLogin();
    } else {
      console.log('用户未登录，跳转到登录页面');
      wx.redirectTo({ url: '/pages/login/login' });
      return;
    }
  },

  /**
   * 执行自动登录
   */
  performAutoLogin() {
    autoLogin().then((userInfo) => {
      console.log('排行榜自动登录成功，用户信息:', userInfo);
      // 自动登录成功，更新页面数据
      this.updateSelectionType();
      this.getRankingData(this.data.selectionType);
      // 重置后台状态
      setAppResumedFromBackground(false);
      // 重置用户在线开始时间
      setUserOnlineStartTime(Date.now());
    }).catch((error) => {
      console.error('排行榜自动登录失败:', error);
      // 自动登录失败，跳转到登录页面
      wx.redirectTo({ url: '/pages/login/login' });
    });
  },

  // 初始化数据
  initData() {
    // 模拟前三名数据
    this.setData({
      topThree: [
        {
          rank: 1,
          teamName: '团队名1',
          department: '某某部门',
          steps: 9222
        },
        {
          rank: 2,
          teamName: '团队名1',
          department: '某某部门',
          steps: 7222
        },
        {
          rank: 3,
          teamName: '团队名1',
          department: '某某部门',
          steps: 6000
        }
      ],
      otherRanks: [
        {
          rank: 4,
          teamName: '团队名1',
          department: '某某部门',
          steps: 6000
        },
        {
          rank: 5,
          teamName: '团队名1',
          department: '某某部门',
          steps: 6000
        },
        {
          rank: 6,
          teamName: '团队名1',
          department: '某某部门',
          steps: 6000
        },
        {
          rank: 7,
          teamName: '团队名1',
          department: '某某部门',
          steps: 6000
        }
      ],
      myRank: {
        rank: 12,
        teamName: '团队名12',
        department: '某某部门',
        steps: 3000
      }
    });
  },

  // 主tab切换
  onMainTabChange(e) {
    const mainTabIndex = Number(e.currentTarget.dataset.index);
    this.setData({ 
      mainTabIndex, 
      subTabIndex: 0 
    }, () => {
      this.updateSelectionType();
      if (mainTabIndex === 2) {
        // 中奖名单
        this.getWinListData();
      } else {
        this.getRankingData(this.data.selectionType);
      }
    });
  },

  // 子tab切换
  onSubTabChange(e) {
    const subTabIndex = Number(e.currentTarget.dataset.index);
    this.setData({ subTabIndex }, () => {
      this.updateSelectionType();
      if (this.data.mainTabIndex === 2) {
        // 中奖名单
        this.getWinListData();
      } else {
        this.getRankingData(this.data.selectionType);
      }
    });
  },

  // 更新选择类型
  updateSelectionType() {
    const { mainTabIndex, subTabIndex } = this.data;
    let selectionType = '';
    
    if (mainTabIndex === 0) { // 团队赛
      selectionType = subTabIndex === 0 ? SelectionType.TEAM_HEAD : SelectionType.TEAM_BRANCH;
    } else if (mainTabIndex === 1) { // 个人赛
      selectionType = subTabIndex === 0 ? SelectionType.PERSONAL_TODAY : 
                     subTabIndex === 1 ? SelectionType.PERSONAL_WEEK : SelectionType.PERSONAL_TOTAL;
    }
    
    this.setData({ selectionType });
  },

  // 获取API参数
  getApiParam(selectionType) {
    const paramMap = {
      [SelectionType.PERSONAL_TODAY]: 'today',
      [SelectionType.PERSONAL_WEEK]: 'week',
      [SelectionType.PERSONAL_TOTAL]: 'total',
      [SelectionType.TEAM_HEAD]: 'head',
      [SelectionType.TEAM_BRANCH]: 'branch'
    };
    return paramMap[selectionType] || 'today';
  },

  // 获取排行榜数据
  getRankingData(selectionType) {
    if (!selectionType) return;
    
    // 检查缓存
    if (this.data.cacheData[selectionType]) {
      this.processRankingData(this.data.cacheData[selectionType]);
      return;
    }
    
    const apiParam = this.getApiParam(selectionType);
    
    wx.request({
      url: API_URL,
      method: 'GET',
      data: { selectionType: apiParam },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          const rankList = res.data.data || [];
          // 缓存数据
          const cacheData = { ...this.data.cacheData };
          cacheData[selectionType] = rankList;
          this.setData({ cacheData });
          
          this.processRankingData(rankList);
        } else {
          this.processRankingData([]);
        }
      },
      fail: () => {
        this.processRankingData([]);
      }
    });
  },

  // 获取中奖名单数据
  getWinListData() {
    // 检查缓存
    if (this.data.winListCache) {
      console.log('Using cached win list data');
      this.processWinListData(this.data.winListCache);
      return;
    }
    
    console.log('Requesting win list data from server');
    wx.request({
      url: WIN_API_URL,
      method: 'GET',
      success: (res) => {
        console.log('getWinListData result:', res.data);
        if (res.data && res.data.code === 200) {
          const winList = res.data.data || [];
          // 缓存中奖名单数据
          this.setData({ winListCache: winList });
          this.processWinListData(winList);
        } else {
          this.processWinListData([]);
        }
      },
      fail: (err) => {
        console.error('getWinListData fail:', err);
        this.processWinListData([]);
      }
    });
  },

  // 处理中奖名单数据
  processWinListData(winList) {
    if (!winList || winList.length === 0) {
      this.setData({
        topThree: [],
        otherRanks: [],
        myRank: null,
        winList: []
      });
      return;
    }

    // 将中奖名单数据转换为排行榜格式
    const formattedWinList = winList.map((item, index) => ({
      rank: index + 1,
      teamName: item.name || '未知用户',
      department: '', // 中奖名单不显示部门
      steps: 0, // 中奖名单不显示步数
      avatar: item.avatar
    }));

    // 分离前三名和其他排名
    const topThree = formattedWinList.slice(0, 3);
    const otherRanks = formattedWinList.slice(3);
    
    this.setData({
      topThree,
      otherRanks,
      myRank: null, // 中奖名单不显示"我的排名"
      winList: formattedWinList
    });
  },

  // 处理排行榜数据
  processRankingData(rankList) {
    if (!rankList || rankList.length === 0) {
      this.setData({
        topThree: [],
        otherRanks: [],
        myRank: null
      });
      return;
    }

    // 分离前三名和其他排名
    const topThree = rankList.slice(0, 3).map(item => ({
      rank: item.rank,
      teamName: item.teamName || item.userName || '未知团队',
      department: item.organization || '某某部门',
      steps: item.steps || 0
    }));

    const otherRanks = rankList.slice(3).map(item => ({
      rank: item.rank,
      teamName: item.teamName || item.userName || '未知团队',
      department: item.organization || '某某部门',
      steps: item.steps || 0
    }));

    // 找到我的排名
    const myRank = rankList.find(item => item.userCode === wx.getStorageSync('userCode'));
    
    this.setData({
      topThree,
      otherRanks,
      myRank: myRank ? {
        rank: myRank.rank,
        teamName: myRank.teamName || myRank.userName || '未知团队',
        department: myRank.organization || '某某部门',
        steps: myRank.steps || 0
      } : null
    });
  }
}); 